<template>
  <div>
    <!-- 旧件入库 - 明细 -->
    <BreakSpace label="通知单信息" :containerStyle="{ marginBottom: '10px' }" />
    <FormPanel ref="formPanel1" :list="formList1" :cols="3" :formType="'add'" labelWidth="100" :isSubmitBtn="false"
      @formChange="formChangeHandle" />
    <div style="padding-top: 3rem;"></div>

    <BreakSpace label="上报信息" :containerStyle="{ marginBottom: '10px' }" />
    <FormPanel ref="formPanel2" :list="formList2" :cols="3" :formType="'add'" labelWidth="110" :isSubmitBtn="false" />
    <div style="padding-top: 3rem;"></div>

    <BreakSpace label="旧件列表" :containerStyle="{ marginBottom: '10px' }" />
    <FilterTable ref="table1" :columns="columns" :params="fetchParams" :dataSource="dataList" :datakey="'items'"
      :onColumnsChange="columns => (this.columns = columns)" :onRowSelectChange="selectChange" selectionType="single"
      height="auto" :isPagination=false :isSelectColumn=false>
    </FilterTable>
    <div style="padding-top: 3rem;"></div>
    <BreakSpace label="操作记录" :containerStyle="{ marginBottom: '10px' }" />
    <FilterTable ref="table2" :columns="caozuojilucolumns" :params="fetchParams" :dataSource="dataList1"
      :datakey="'items'" :onColumnsChange="columns => (this.columns = columns)" :onRowSelectChange="selectChange"
      selectionType="single" height="auto" :isPagination=false :isSelectColumn=false>
    </FilterTable>
    <div style="margin-bottom: 1rem;"></div>
    <div style="padding-top: 3rem;"></div>
    <div :style="{
      position: 'absolute',
      left: 0,
      bottom: 0,
      right: 0,
      zIndex: 9,
      borderTop: '1px solid #e9e9e9',
      padding: '10px 20px',
      background: '#fff',
      textAlign: 'right'
    }">
      <multiuse-button @click="closeDialog">关 闭</multiuse-button>
    </div>
  </div>
</template>
<script>
import { getPartType } from '@/api/dictionary/index.js';
import { selectById, findFileByUrl, getUserInfo } from '@/api/usedPartsReturnManage/usedPartsReturn_OEM/usedPartsWarehousing';
import { dictionary } from '@/utils/dictMixin';
export default {
  props: ['rowData'],
  mixins: [dictionary],
  components: {

  },
  data() {
    return {
      uploadJfHiddenFlag: true,
      jfDisableButton: true,
      dataList: [],
      dataList1: [],
      visible: false,
      visibleDrawer: false,
      selectDelearFlag: false,
      collapse: false,
      infoId: null,
      flterValue: {}, //参数
      //上报信息
      columns: this.creatHeader(),
      //操作记录
      caozuojilucolumns: this.caozuojilu(),
      fetchParams: {}, //ipa 接口
      selectedRows: [], //选中服务站
      //通知单信息
      formList1: this.createFormList(),
      formList2: this.createformListshangbao(),
      saveData: null
    };
  },
  created() {
    // this.chuqi();
    this.chuqi2();
    this.chuqi3();
    this.chuqi4();
    this.chuqi5();
    /* this.chuqi6(); */
    this.init(this.rowData.returnId);

  },
  methods: {
    // 获取服务端文件 to blob
    async downLoadByUrl(url, params = {}) {
      let res = await findFileByUrl(url);
      console.log(res.data)
      return res.data;
    },
    async init(val) {
      let newVar = await selectById({ id: val })
      if (newVar.data.returnType === 55951001) {
        this.jfDisableButton = false;
      }
      else {
        this.uploadJfHiddenFlag = false;
      }
      this.editData = newVar.data;
      console.log("=== 通过ID查询结果返回 ==== ", newVar, " ======");
      this.formList1.forEach(x => {
        if (this.jfDisableButton) {
          if (x.fieldName == 'wholeReturn') {
            x.hidden = false;
          }
          if ((x.fieldName == 'pickUpPerson' || x.fieldName == 'certificateNo') && newVar.data.expressType === 55211004) {
            x.hidden = false;
          }
          if ((x.fieldName == 'expressAddress' || x.fieldName == 'cPerson' || x.fieldName == 'cTel') && newVar.data.expressType === 55211004) {
            x.hidden = true;
          }
        }
        console.log(newVar);
        x.initialValue = newVar.data[x.fieldName];
        if (x.fieldName == 'partNum') {
          x.initialValue = this.rowData.partNum;
        }
      });

      //文件地址转换
      // let tempFileArr =[];
      // for (let i = 0; i < newVar.data.fileList.length; i++) {
      //   let current = newVar.data.fileList[i];
      //   let res = await findFileByUrl(current.fileUrl);
      //   if (res) {
      //     current.fileUrl = res.data;
      //     tempFileArr.push(current);
      //   }
      // }
      /*  this.formList2.forEach(x => {
         x.initialValue = newVar.data[x.fieldName];
         if (x.fieldName == 'fileList') {
           x.initialValue = newVar.data.fileList.map((f) => ({name: f.title, url: f.fileUrl}));
         }
       }); */

      for (const x of this.formList2) {
        if (this.jfDisableButton) {
          if (x.type == 'BREAK_SPACE') {
            x.hidden = false;
          }
          if ((x.fieldName == 'certificateNoPic' || x.fieldName == 'pickUpPic' || x.fieldName == 'partPic') && newVar.data.expressType === 55211004) {
            x.hidden = false;
          }
          if ((x.fieldName == 'expressPic') && newVar.data.expressType === 55211005) {
            x.hidden = false;
          }
        }
        if (this.jfDisableButton && (x.fieldName == 'certificateNoPic' || x.fieldName == 'pickUpPic' || x.fieldName == 'partPic' || x.fieldName == 'expressPic')) {
          if (newVar.data[x.fieldName] == null) {
            x.initialValue = [];
          } else {
            let realUrl = newVar.data[x.fieldName].split("?")[0]
            let picUrl = await this.downLoadByUrl(realUrl)
            x.initialValue = [picUrl];
          }
        } else {
          x.initialValue = newVar.data[x.fieldName];
        }
        if (x.fieldName == 'fileList') {
          x.initialValue = newVar.data.fileList.map((f) => ({ name: f.title, url: f.fileUrl }));
        }
      };
      this.$refs.table1.$refs.pageTable.EXECUTE_INSERT(newVar.data.dtlList);
      //回运状态是新建或已回运，查询店端员工数据55881001 55881004,紧急回运第一条保留不查店端
      const empData = await getUserInfo();
      let newLogList = [];
      newVar.data.logList.forEach((x, index) => {
        if (newVar.data.returnType && newVar.data.returnType == 55951002 && index == 0) {
          //紧急回运第一条保留不查店端
        } else if (x.checkBy && empData && (x.checkStatus === 55881001 || x.checkStatus === 55881004)) {
          let userData = empData.data.find(item => item.userId == x.checkBy);
          if (userData) {
            x.checkByStr = userData.userName;
          }
        }
        newLogList.push(x);
      });
      this.$refs.table2.$refs.pageTable.EXECUTE_INSERT(newLogList);
      // this.$refs.table2.$refs.pageTable.EXECUTE_INSERT(newVar.data.logList);
      if (this.rowData.statusStr === '已回运') {
        this.formList1.find(x => x.fieldName == 'str').hidden = false;
        this.formList1.find(x => x.fieldName == 'str').initialValue = this.rowData.statusStr;
        this.flag = false;
      } else {
        this.formList1.find(x => x.fieldName == 'str').hidden = true;
        this.formList1.find(x => x.fieldName == 'returnStatus').hidden = false;
      }

    },

    //旧件状态
    // async chuqi() {
    //   console.log("===== 获取下拉框数据 ====== ")
    //   const res = await getPartType({ type: 5585 });
    //   console.log("==========",res)
    //   if (res.resultCode == 200) {
    //     this.columns.find(x => x.dataIndex == 'partStatus').initialValue = '';
    //     this.columns.find(x => x.dataIndex == 'partStatus').editItems = res.data.map(y => ({ text: y.codeCnDesc, value: y.codeId }));
    //   }
    // },
    //运输方式下拉框
    async chuqi2() {
      console.log("===== 获取下拉框数据 ====== ")
      const res = await getPartType({ type: 5521 });
      console.log("==========", res)
      if (res.resultCode == 200) {
        this.formList2.find(x => x.fieldName == 'expressType').initialValue = '';
        this.formList2.find(x => x.fieldName == 'expressType').itemList = res.data.map(y => ({ text: y.codeCnDesc, value: y.codeId }));
      }
    },
    //单据状态
    async chuqi3() {
      console.log("===== 获取下拉框数据 ====== ")
      const res = await getPartType({ type: 5588 });
      console.log("==========", res)
      if (res.resultCode == 200) {
        this.formList1.find(x => x.fieldName == 'returnStatus').initialValue = '';
        this.formList1.find(x => x.fieldName == 'returnStatus').itemList = res.data.map(y => ({ text: y.codeCnDesc, value: y.codeId }));
      }
    },
    //入库说明
    async chuqi4() {
      console.log("===== 获取下拉框数据 ====== ")
      const res = await getPartType({ type: 5590 });
      console.log("==========", res)
      if (res.resultCode == 200) {
        this.columns.find(x => x.dataIndex == 'inInfo').initialValue = '';
        this.columns.find(x => x.dataIndex == 'inInfo').editItems = res.data.map(y => ({ text: y.codeCnDesc, value: y.codeId }));
      }
    },
    //是否整单回运
    async chuqi5() {
      console.log("===== 获取下拉框数据 ====== ")
      const res = await getPartType({ type: 1004 });
      console.log("==========", res)
      if (res.resultCode == 200) {
        this.formList1.find(x => x.fieldName == 'wholeReturn').initialValue = '';
        this.formList1.find(x => x.fieldName == 'wholeReturn').itemList = res.data.map(y => ({ text: y.codeCnDesc, value: y.codeId }));
      }
    },
    //装箱属性
    /*  async chuqi6() {
       console.log("===== 获取下拉框数据 ====== ")
       const res = await getPartType({ type: 5591 });
       console.log("==========",res)
       if (res.resultCode == 200) {
         this.columns.find(x => x.dataIndex == 'boxAttrStr').initialValue = '';
         this.columns.find(x => x.dataIndex == 'boxAttrStr').editItems = res.data.map(y => ({ text: y.codeCnDesc, value: y.codeId }));
       }
     }, */
    formChangeHandle(val) {
      console.log(val);
      this.saveData = val;
    },
    //搜索获取数据
    changeHandle(val) {
      this.fetchParams = val;
      console.log(val);
    },
    //选中
    selectChange(rows) {
      this.selectedRows = rows;
      console.log(this.selectedRows);
    },
    //保存
    saveDialog() {
      this.$refs.formPanel1.SUBMIT_FORM();
      if (this.saveData) {
        this.$emit('save', this.selectedRows);
      }
    },
    //取消操作
    closeDialog() {
      this.$emit('close', { visible: false, data: this.selectedRows, type: 'close' });
    }, //服务站选择页面
    SelectDelear() {
      this.selectDelearFlag = true;
    }, //关闭
    Delearclose() {
      this.selectDelearFlag = false;
    },
    //保存
    Delearsave() {
      this.selectDelearFlag = false;
      this.fetchParams = { ...this.fetchParams };
    },
    chooseOrderNo() {
      this.visible = true;
    },
    add() { },
    //通知单信息
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '通知单号',
          fieldName: 'returnNo',
          disabled: true, // 置会
          readonly: true // 只读
        },
        {
          type: 'INPUT',
          label: '服务中心代码',
          fieldName: 'showOwnerCode',
          disabled: true, // 置会
          readonly: true // 只读
        },
        {
          type: 'INPUT',
          label: '服务中心名称',
          fieldName: 'dealerName',
          disabled: true, // 置会
          readonly: true // 只读
        },
        {
          type: 'SELECT',
          label: '单据状态',
          fieldName: 'returnStatus',
          initialValue: '',
          itemList: [],
          readonly: true, // 只读
          disabled: true, // 置会
          hidden: true
        },
        {
          type: 'INPUT',
          label: '单据状态',
          fieldName: 'str',
          readonly: true,// 只读
          disabled: true, // 置会
          hidden: false
        },
        {
          type: 'INPUT',
          label: '旧件数量',
          fieldName: 'partNum',
          disabled: true, // 置会
          readonly: true // 只读
        },
        /* {
          type: 'INPUT',
          label: '回运单号',
          fieldName: 'returnNo',
          disabled: true, // 置会
          readonly: true // 只读
        }, */
        {
          type: 'INPUT',
          label: '联系人',
          fieldName: 'cPerson',
          disabled: true, // 置会
          readonly: true // 只读
        },
        {
          type: 'INPUT',
          label: '联系人电话',
          fieldName: 'cTel',
          readonly: true, // 只读
          disabled: true //置灰
        },
        {
          type: 'INPUT',
          label: '取件人',
          placeholder: '请输入取件人...',
          fieldName: 'pickUpPerson',
          readOnly: true,
          disabled: true,
          hidden: true,
        },
        {
          type: 'INPUT',
          label: '取件人身份证',
          fieldName: 'certificateNo',
          readOnly: true,
          disabled: true,
          hidden: true,
        },
        {
          type: 'INPUT',
          label: '旧件仓库',
          fieldName: 'whName',
          disabled: true, // 置会
          readonly: true // 只读
        },
        {
          type: 'INPUT',
          label: '邮寄地址',
          placeholder: '请输入邮寄地址...',
          fieldName: 'expressAddress',
          readonly: true, // 只读
          disabled: true //置灰
        },
        {
          type: 'SELECT',
          label: '是否整单回运',
          fieldName: 'wholeReturn',
          initialValue: '',
          itemList: [],
          disabled: true, // 置会
          readonly: true, // 只读
          hidden: true
        },
      ];
    },
    //上报信息
    createformListshangbao() {
      return [
        {
          type: 'SELECT',
          label: '运输方式',
          fieldName: 'expressType',
          readonly: true, // 只读
          disabled: true, // 置会
          itemList: []
        },
        {
          type: 'INPUT',
          label: '物流公司',
          fieldName: 'expressCompany',
          disabled: true, // 置会
          readonly: true // 只读
        },
        {
          type: 'INPUT',
          label: '物流单号',
          fieldName: 'expressNo',
          disabled: true, // 置会
          readonly: true // 只读
        },
        {
          type: 'INPUT',
          label: '包装箱数',
          fieldName: 'boxCounts',
          disabled: true, // 置会
          readonly: true // 只读
        },
        {
          type: 'INPUT',
          label: '纸箱数量',
          fieldName: 'paperCounts',
          disabled: true, // 置会
          readonly: true // 只读
        },
        {
          type: 'INPUT',
          label: '木箱数量',
          fieldName: 'woodCounts',
          disabled: true, // 置会
          readonly: true // 只读
        },
        {
          type: 'INPUT',
          label: '编织袋数量',
          fieldName: 'ironCounts',
          disabled: true, // 置会
          readonly: true // 只读
        },
        {
          type: 'INPUT',
          label: '裸件数量',
          fieldName: 'bareParts',
          disabled: true, // 置会
          readonly: true // 只读
        },
        {
          type: 'DATE',
          label: '回运时间',
          fieldName: 'dlDate',
          valueFormat: 'yyyy-MM-dd',
          readonly: true, // 只读
          disabled: true // 置会
        },
        {
          type: 'TEXT_AREA',
          label: '备注',
          fieldName: 'remarks',
          readonly: true, // 只读
          disabled: true, // 置会
          selfCols: 3,// 元素占据几行
          rows: 3
        },
        {
          type: 'UPLOAD_FILE',
          label: '查看文件',
          fieldName: 'fileList',
          placeholder: '选择文件...',
          disabled: true, //置灰
          readonly: true,// 只读
          upload: {
            actionUrl: '/api/file/oss/upload',
            limit: 10,
            tipText: '（支持PDF、RAR、JPG格式）'
          },
          hidden: !this.uploadJfHiddenFlag,
        },
        {
          type: 'BREAK_SPACE',
          label: '快返附件',
          hidden: true
        },
        {
          type: 'UPLOAD_IMG',
          label: '保修旧件图片',
          fieldName: 'partPic',
          placeholder: '上传索保修旧件图片...',
          selfCols: 1,
          initialValue: [],
          rules: [{ required: true, message: '请上传索赔件图片', trigger: 'change' }],
          upload: {
            // actionUrl: config.uploadUrl+'/api/file/oss/upload',
            // actionUrl: `${config.uploadUrl}/api/file/v1/file/upload`,
            actionUrl: '/api/file/oss/upload',
            fixedSize: [5, 3],
            limit: 1,
            isCalcHeight: true,
            isFileName: true,
            isPreview: true
          },
          hidden: true,
          disabled: true, //置灰
          readonly: true // 只读
        },
        {
          type: 'UPLOAD_IMG',
          label: '取件人凭证',
          fieldName: 'pickUpPic',
          placeholder: '上传取件人凭证...',
          selfCols: 1,
          initialValue: [],
          rules: [{ required: true, message: '请上传取件人凭证', trigger: 'change' }],
          upload: {
            // actionUrl: config.uploadUrl+'/api/file/oss/upload',
            // actionUrl: `${config.uploadUrl}/api/file/v1/file/upload`,
            actionUrl: '/api/file/oss/upload',
            fixedSize: [5, 3],
            limit: 1,
            isCalcHeight: true,
            isFileName: true,
            isPreview: true
          },
          hidden: true,
          disabled: true, //置灰
          readonly: true // 只读
        },
        {
          type: 'UPLOAD_IMG',
          label: '取件人身份证凭证照片',
          fieldName: 'certificateNoPic',
          placeholder: '上传取件人身份证凭证照片...',
          selfCols: 1,
          initialValue: [],
          rules: [{ required: true, message: '请上传取件人身份证凭证照片', trigger: 'change' }],
          upload: {
            // actionUrl: config.uploadUrl+'/api/file/oss/upload',
            // actionUrl: `${config.uploadUrl}/api/file/v1/file/upload`,
            actionUrl: '/api/file/oss/upload',
            fixedSize: [5, 3],
            limit: 1,
            isCalcHeight: true,
            isFileName: true,
            isPreview: true
          },
          hidden: true,
          disabled: true, //置灰
          readonly: true // 只读
        },
        {
          type: 'UPLOAD_IMG',
          label: '快递凭证',
          fieldName: 'expressPic',
          placeholder: '上传快递凭证...',
          selfCols: 1,
          initialValue: [],
          rules: [{ required: true, message: '请上传快递凭证', trigger: 'change' }],
          upload: {
            // actionUrl: config.uploadUrl+'/api/file/oss/upload',
            // actionUrl: `${config.uploadUrl}/api/file/v1/file/upload`,
            actionUrl: '/api/file/oss/upload',
            fixedSize: [5, 3],
            limit: 1,
            isCalcHeight: true,
            isFileName: true,
            isPreview: true
          },
          hidden: true,
          disabled: true, //置灰
          readonly: true // 只读
        },
        {
          type: 'UPLOAD_FILE',
          label: '查看文件',
          fieldName: 'fileList',
          placeholder: '选择文件...',
          disabled: true, //置灰
          readonly: true,// 只读
          upload: {
            actionUrl: '/api/file/oss/upload',
            limit: 10,
            tipText: '（支持PDF、RAR、JPG格式）'
          },
          hidden: this.uploadJfHiddenFlag,
        },
      ];
    },
    //旧件列表
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        { title: '是否主因件', dataIndex: 'isMain', sorter: true },
        { title: '索赔单号', dataIndex: 'cmsClaimNo', sorter: true },
        { title: '旧件代码', dataIndex: 'partCode', sorter: true },
        { title: '旧件名称', dataIndex: 'partName', sorter: true },
        { title: '数量', precision: 0, dataIndex: 'actualPartCount', sorter: true },
        {
          title: '入库数量',
          dataIndex: 'inCount',
          sorter: true,
          minWidth: 120,
          editable: true,
          defaultEditable: true,
          showOverflowTooltip: true,
          editType: 'input',
          disabled: true // 置会
        },
        {
          title: '合格数量',
          dataIndex: 'qualifiedCount',
          sorter: true,
          minWidth: 120,
          editable: true,
          defaultEditable: true,
          showOverflowTooltip: true,
          editType: 'input',
          disabled: true // 置会
        },
        {
          title: '不合格数量',
          dataIndex: 'unqualifiedCount',
          sorter: true,
          minWidth: 120,
          editable: true,
          defaultEditable: true,
          showOverflowTooltip: true,
          editType: 'input',
          disabled: true // 置会
        },
        {
          title: '入库说明',
          dataIndex: 'inInfo',
          sorter: true,
          minWidth: 120,
          // editable: true,
          editType: 'select',
          editItems: [],
          disabled: true // 置会
        },
        { title: '责任商代码', dataIndex: 'responsibleCode', sorter: true },
        { title: '责任商名称', dataIndex: 'responsiblePerson', sorter: true },
        { title: 'VIN', dataIndex: 'vin', sorter: true, width: 150 },
        { title: '车型名称', dataIndex: 'modelName', sorter: true },
        { title: '索赔类型', dataIndex: 'cmsClaimTypeStr', sorter: true },
       /*  {
          title: '车辆属性', dataIndex: 'ifComm', sorter: true, filterItems: this.createDictList('5543'),
          dictItems: this.createDictList('5543'),
          render: props => {
            return <span>{this.createDictText(props.row.ifComm, '5543')}</span>;
          }
        }, */
        { title: '采购渠道代码', dataIndex: 'channelCode', sorter: true },
        { title: '采购渠道名称', dataIndex: 'channelName', sorter: true },
        { title: '装箱号', dataIndex: 'boxNo', sorter: true },
        /*  {
          title: '装箱属性',
          dataIndex: 'boxAttrStr',
          sorter: true,
          minWidth: 120,
          editable: true,
          defaultEditable: true,
          showOverflowTooltip: true,
          initialValue: '',
          editType: 'select',
          editItems: [],
          disabled: true
        }, */
        { title: '入库仓库', dataIndex: 'whName', sorter: true },
      /*   {
          title: '旧件状态',
          dataIndex: 'statusStr',
          sorter: true,
          minWidth: 120,
          editable: true,
          defaultEditable: true,
          showOverflowTooltip: true,
          editType: 'select',
          editItems: [],
          disabled: true // 置会
        },
 */
        {
          title: '备注',
          dataIndex: 'inInfoRemarks',
          sorter: true,
          filter: true,
          minWidth: 300,
          filterType: 'input',
          // editable: true,
          defaultEditable: false,
          editType: 'text',
          disabled: true,
          // editRequired: true,
          // rules: [
          //   { max: 200, message: '长度最大50字符', trigger: 'blur' }
          // ]
          render: props => {
            return <div>
              <el-input v-model={props.row.inInfoRemarks} disabled="true"
                placeholder="" maxlength="50">
              </el-input>
            </div>;
          }
        },
      ];
    },
    //操作记录
    caozuojilu() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        { title: '操作人', dataIndex: 'checkByStr', sorter: true },
        { title: '操作时间', dataIndex: 'checkAt', sorter: true },
        // {title: '操作类型', dataIndex: 'checkStatus2', sorter: true},
        { title: '操作后状态', dataIndex: 'statusStr', sorter: true },
        // {title: '操作备注', dataIndex: 'checkRemarks', sorter: true}
      ];
    }
  }
};
</script>
<style lang="less" scoped>

</style>
